import React, { Component } from 'react'
import './index.css'

const MyContext = React.createContext()
const { Provider, Consumer } = MyContext

export default class A extends Component {
  state = {
    username: 'mal'
  }
  render() {
    return (
      <div className='parent'>
        <h2>我是A组件</h2>
        <Provider value={this.state.username}>
          <B />
        </Provider>
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div className='son'>
        <h2>我是B组件</h2>
        <C />
      </div>
    )
  }
}

// class C extends Component {
//   static contextType = MyContext  // 声明一下context
//   render() {
//     return (
//       <div className='son-son'>
//         <h2>我是C组件</h2>
//         <h2>我接受到的A组件的值为:{this.context}</h2>
//       </div>
//     )
//   }
// }

// 函数式组件中使用xxxContext.Consumer 
function C() {
  return (
    <div className='son-son'>
      <h2>我是C组件</h2>
      <h2>我接受到的A组件的值为:
        <Consumer>
          {
            value => value
          }
        </Consumer>
      </h2>
    </div>
  )
}
